package com.chaos.auth.config.handler;

import com.chaos.framework.model.dto.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class AuthenticationFailureHandler implements org.springframework.security.web.authentication.AuthenticationFailureHandler {

    private final ObjectMapper objectMapper;

    public AuthenticationFailureHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        Result result;
//        if (exception instanceof OAuth2AuthenticationException oauth2Exception) {
//            OAuth2Error error = oauth2Exception.getError();
//            OAuth2ErrorCode resultCode = OAuth2ErrorCode.getByOAuth2Error(error.getErrorCode());
//            String message = error.getDescription() != null ? resultCode.message() + ", " + error.getDescription() : resultCode.message();
//
//            result = Results.failure(resultCode.code(), message);
//        } else {
//            result = Results.failure("", exception.getMessage());
//        }
        log.error("[{}] {}", request.getMethod()
                , request.getRequestURL() + "?" + request.getQueryString(), exception);
        objectMapper.writeValue(response.getWriter(), null);
    }

}
